package com.walter.gateway.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author Walter
 * @date 2025/2/5 下午5:15
 **/
@Slf4j
@Component
public class UniFormatGlobalFilter implements GlobalFilter, Ordered {
    // 用于 JSON 序列化
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        // 合并多个 DataBuffer
                        DataBufferFactory dataBufferFactory = bufferFactory;
                        DataBuffer joinedBuffer = dataBufferFactory.allocateBuffer();
                        dataBuffers.forEach(joinedBuffer::write);

                        // 读取 response body 内容
                        byte[] content = new byte[joinedBuffer.readableByteCount()];
                        joinedBuffer.read(content);
                        DataBufferUtils.release(joinedBuffer);
                        String responseBody = new String(content, StandardCharsets.UTF_8);

                        try {
                            // 尝试将原始响应 body 解析为 JSON (假设后端服务返回 JSON)
                            Object originalData = objectMapper.readValue(responseBody, Object.class);
                            // 包装成统一响应格式
                            CommonResult<Object> wrappedResponse = CommonResult.success(originalData);
                            byte[] wrappedBytes = objectMapper.writeValueAsBytes(wrappedResponse);

                            // 修改 response body 为统一格式
                            originalResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON); // 设置 Content-Type 为 JSON
                            return bufferFactory.wrap(wrappedBytes);

                        } catch (JsonProcessingException e) {
                            // 如果原始响应 body 不是 JSON 格式，或者解析出错，则原样返回 (或者根据需要处理)
                            log.warn("Failed to parse response body as JSON, returning original body.  Error: {}", e.getMessage());
                            return bufferFactory.wrap(content); // 原样返回
                        }
                    }));
                }
                // body 不是 Flux 的情况，直接返回
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 1; // 确保在 响应写入之前执行，但优先级低于 异常处理
    }
}
